<template>
  <div class="app-container">
    <h2 style="text-align: center">添加历史人物</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="人物基本信息" />
      <el-step title="人物地点" />
      <el-step title="人物总结" />
    </el-steps>

    <el-form label-width="120px" v-if="hasPerm('figure.add')">
      <el-form-item label="人物名">
        <el-input
          v-model="history_figure.figureName"
          clearable
          style="width: 500px"
        />
      </el-form-item>

      <el-form-item label="人物类型">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="checkedforms"
          @change="handleCheckedFromsChange"
        >
          <el-checkbox v-for="form in forms" :label="form" :key="form">{{
            form
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="年龄">
        <el-input-number
          v-model="history_figure.age"
          controls-position="right"
          :min="1"
          :max="120"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="history_figure.sex" clearable placeholder="请选择">
          <!--
            数据类型一定要和取出的json中的一致，否则没法回填
            因此，这里value使用动态绑定的值，保证其数据类型是number
          -->
          <el-option :value="1" label="男" />
          <el-option :value="2" label="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="出生时间">
        <el-date-picker
          v-model="history_figure.birthday"
          type="date"
          placeholder="选择人物的出生日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item label="死亡时间">
        <el-date-picker
          v-model="history_figure.deathDay"
          type="date"
          placeholder="选择人物的死亡日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item label="湖南地级市">
        <el-select
          v-model="history_figure.city"
          clearable
          placeholder="请选择"
          @change="cityChange"
        >
          <el-option
            v-for="city in cities"
            :key="city.value"
            :label="city.label"
            :value="city.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input
          style="width: 300px"
          v-model="history_figure.hometown"
          placeholder="请输入地点"
          clearable
          @change="convertLoc"
        />
        <position ref="position"></position>
      </el-form-item>

      <el-form-item label="经度">
        <el-input
          style="width: 220px"
          v-model="history_figure.longitude"
          clearable
        />
      </el-form-item>

      <el-form-item label="纬度">
        <el-input
          style="width: 220px"
          v-model="history_figure.latitude"
          clearable
        />
      </el-form-item>

      <!-- 人物肖像 -->
      <el-form-item label="人物肖像">
        <!-- 头衔缩略图 -->
        <pan-thumb :image="history_figure.portrait" />
        <!-- 文件上传按钮 -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="imagecropperShow = true"
          >更换肖像
        </el-button>
        <!--
v-show：是否显示上传组件
:key：类似于id，如果一个页面多个图片上传控件，可以做区分
:url：后台上传的url地址
@close：关闭上传组件
@crop-upload-success：上传成功后的回调 -->
        <image-cropper
          v-show="imagecropperShow"
          :width="300"
          :height="300"
          :key="imagecropperKey"
          :url="BASE_API + '/gis/fileoss'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </el-form-item>

      <el-form-item align="right">
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >{{ btuTitle }}</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import figure from "@/api/figure/figure";
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";
import position from '../../components/Area/position'
import city from "@/api/option/city";
import history_type from "@/api/option/history_type";
export default {
  components: { ImageCropper, PanThumb, position },
  data() {
    return {
      history_figure: {
        figureName: "",
        age: "",
        sex: "",
        birthday: null,
        deathDay: null,
        city:'',
        hometown: "",
        longitude: "",
        latitude: "",
        portrait: "",
        types: "",
      }, //历史人物
      imagecropperShow: false, //上传弹框组件是否显示
      imagecropperKey: 0, // 上传组件的key值
      BASE_API: process.env.BASE_API, // 接口API地址
      saveBtnDisabled: false, // 保存按钮是否禁用
      figureId: "", //事件id
      fileList: [], //上传文件列表
      isIndeterminate: true,
      checkedforms: [], //已选择的类型
      forms: [], //可选择的类型
      checkAll: false, //是否全选
      btuTitle: "保存并下一步",
      hasPermission: true, //是否有权限
      cities: [], //城市
    };
  },

  created() {
    this.getFigureTypes();
    this.getCities();
    if (this.$route.params && this.$route.params.id) {
      // params.id 中 id 和路由中的 占位符有关系
      this.figureId = this.$route.params.id;
      this.getFigureInfo();
    }
    this.hasPermission = this.hasPerm("location.add");
    if (!this.hasPermission) {
      this.btuTitle = "保存";
    }
  },

  methods: {
    // 获得所有的城市列表
    getCities() {
      city.getCities().then((res) => {
        const cities = res.data.cities;
        cities.forEach((item) => {
          this.cities.push({
            lable: item.id,
            value: item.city,
          });
        });
      });
    },
    getFigureTypes() {
      history_type.getFigureTypes().then((res) => {
        const types = res.data.figureTypes;
        types.forEach((item) => {
          this.forms.push(item.ftype);
        });
      });
    },
    cityChange() {
      this.$refs.position.city = this.history_figure.city;
    },
    //   类型选择
    handleCheckedFromsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.forms.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.forms.length;
    },
    //   类型全选
    handleCheckAllChange(val) {
      // console.log(val)
      this.checkedforms = val ? this.forms : [];
      this.isIndeterminate = false;
    },
    // 关闭弹窗
    close() {
      this.imagecropperShow = false;
      // 当这个 组件 id 变化时 组件会被初始化
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    // 上传成功
    cropSuccess(data) {
      this.imagecropperShow = false;
      // 上传之后接口返回地址
      this.history_figure.portrait = data.url;
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    addFigureInfo() {
      figure.addFigureInfo(this.history_figure).then((res) => {
        // 提示信息
        this.$message({
          type: "success",
          message: res.message,
        });
        const id = res.data.figureId;
        if (this.hasPermission) {
          // 跳转到第二步
          this.$router.push({ path: "/figure/location/" + id });
        } else {
          this.$router.push({ path: "/figure/list" });
        }
      });
    },
    updateFigureInfo() {
      figure.updateFigureInfo(this.history_figure).then((res) => {
        // 提示信息
        this.$message({
          type: "success",
          message: res.message,
        });
        const id = this.figureId;
        if (this.hasPermission) {
          // 跳转到第二步
          this.$router.push({ path: "/figure/location/" + id });
        } else {
          this.$router.push({ path: "/figure/list" });
        }
      });
    },
    saveOrUpdate() {
      // 判断是添加还是修改
      var str = "";
      if (this.checkedforms.length > 0) {
        this.checkedforms.forEach((item) => {
          str = str + item + ",";
        });
        str = str.slice(0, str.length - 1);
      }
      this.history_figure.types = str;
      if (!this.figureId) {
        // 添加
        this.addFigureInfo();
      } else {
        this.updateFigureInfo();
      }
    },
    getFigureInfo() {
      figure.getFigureInfo(this.figureId).then((res) => {
        this.history_figure = res.data.figure;
        if (this.history_figure.types) {
          this.checkedforms = this.history_figure.types.split(",");
        }
        var lat = this.history_figure.latitude;
        var lng = this.history_figure.longitude;
        if (lat && lng) {
          this.$refs.position.lat = lat;
          this.$refs.position.lng = lng;
          this.$refs.position.addOverlay(this.history_figure.hometown);
        }
      });
    },
    convertLoc() {
      this.$refs.position.getInfo(this.history_figure.hometown).then((res) => {
        this.history_figure.latitude = res.lat;
        this.history_figure.longitude = res.lng;
      });
    },
  },
};
</script>

<style scoped>
</style>
